package com.party.jackclientandroid.ui_mine.my_wallet;

import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseActivityTitle;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.base.MyException;
import com.party.jackclientandroid.base.MyTextWatcher;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.CashBean;
import com.party.jackclientandroid.bean.PayResult;
import com.party.jackclientandroid.controller.CashController;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.PayController;
import com.party.jackclientandroid.event.AuthResultEvent;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.utils.CommonUtil;
import com.party.jackclientandroid.utils.Utils;
import com.party.jackclientandroid.view.ShowAccountLayout;
import com.party.jackclientandroid.widget.InputPayPasswordView;
import com.party.jackclientandroid.wxapi.WXPayUtils;
import com.zyyoona7.popup.EasyPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 钱包界面
 */
public class CashActivity extends BaseActivityTitle {
    @BindView(R.id.et_money)
    EditText et_money;
    @BindView(R.id.tip_text)
    TextView tipText;
    @BindView(R.id.btn_cash_withdraw)
    Button btnCashWithdraw;
    @BindView(R.id.tv_cash_balance)
    TextView tvCashBalance;

    @BindView(R.id.account_image)
    ImageView accountImage;

    @BindView(R.id.account_name)
    TextView accountText;

    @BindView(R.id.account_ll)
    LinearLayout account_ll;

    @BindView(R.id.cash_all)
    TextView cash_all;

    private CashBean mCashBean;
    private CashBean.Account currentAccount;
    private CashController cashController;
    String money;
    UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_cash);
        ButterKnife.bind(this);
        setTitle("提现");
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private BigDecimal current, rate;

    private void initData() {
        money = getIntent().getStringExtra("money");
        userService = new UserService(mActivity);
        cashController = new CashController(mActivity, btnCashWithdraw);
        addDisposableIoMain(userService.getPayBankInfo(), new DefaultConsumer<CashBean>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CashBean> baseBean) {
                mCashBean = baseBean.getData();

                if (mCashBean.getWxAccount() != null) {
                    setWxInfo(mCashBean.getWxAccount());
                } else if (mCashBean.getAliAccount() != null) {
                    setAliInfo(mCashBean.getAliAccount());
                }
                current = new BigDecimal(money);
                rate = new BigDecimal(mCashBean.getRate()).multiply(new BigDecimal(100));
                tipText.setText("提现手续费 ¥ 0元 (费率" + Utils.clearZero(rate.toBigInteger()) + "% 最低收取" + mCashBean.getMinRate() + "元)");
            }
        });


        tvCashBalance.setText(money);
        et_money.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                String minRate = mCashBean.getMinRate();
                try {
                    if (".".equals(s.toString())) {
                        et_money.setText("");
                        return;
                    }
                    BigDecimal input = new BigDecimal(s.toString());
                    if (input.compareTo(current) > 0) {
                        et_money.setText(money);
                        input = new BigDecimal(money);
                    }
                    BigDecimal multiply = input.multiply(new BigDecimal(mCashBean.getRate()));
                    if (multiply.compareTo(new BigDecimal(1)) == 1) {
                        minRate = multiply.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                    }

                    tipText.setText("提现手续费 ¥ " + minRate + " (费率" + Utils.clearZero(rate.toBigInteger()) + "% 最低收取" + mCashBean.getMinRate() + "元)");
                } catch (Exception e) {
                    tipText.setText("提现手续费 ¥ " + minRate + " (费率1% 最低收取1元)");
                }
            }
        });
    }

    public void setAliInfo(CashBean.Account aliInfo) {
        currentAccount = aliInfo;
        accountImage.setImageResource(R.mipmap.zhifubao);
        accountText.setText("支付宝（" + mCashBean.getAliAccount().getUserName() + ")");

    }

    public void setWxInfo(CashBean.Account wxInfo) {
        currentAccount = wxInfo;
        accountImage.setImageResource(R.mipmap.weixin);
        accountText.setText("微信（" + mCashBean.getWxAccount().getUserName() + ")");
    }


    @OnClick(R.id.account_ll)
    public void selectAccount(View v) {
        hideSoftInput(mActivity, et_money);
        cashController.show(mCashBean, (View vv) -> {
            String flag = (String) vv.getTag();
            if ("wx".equals(flag)) {
                if (mCashBean.getWxAccount() != null) {
                    setWxInfo(mCashBean.getWxAccount());
                } else {
                    DialogController.showConfirmDialog(mActivity, "温馨提示", "你尚未绑定微信支付", "立即绑定", (View wx) -> {
                        wxAuth();
                    });
                }
            } else if ("ali".equals(flag)) {
                if (mCashBean.getAliAccount() != null) {
                    setAliInfo(mCashBean.getAliAccount());
                } else {
                    DialogController.showConfirmDialog(mActivity, "温馨提示", "你尚未绑定支付", "立即绑定", (View ali) -> {
                        startActivity(BindingAccountZfbActivity.class);
                    });
                }
            }
        });
    }

    @OnClick(R.id.cash_all)
    public void cashAll() {
        et_money.setText(money);
    }

    @OnClick(R.id.btn_cash_withdraw)
    public void cashMoney(View v) {
        String money = et_money.getText().toString();
        if (money.trim().length() == 0) {
            showToast("请输入现金");
            return;
        }
        if (Double.parseDouble(money) < 1) {
            showToast("最低 1元");
            return;
        }
        if (currentAccount == null) {
            showToast("没有可用账号");
            return;
        }
        commitCash(currentAccount.getCardType() + "");
    }

    private EasyPopup passwordPopup;

    public void showAccount(CashBean.Account account) {
        hideSoftInput(mActivity, et_money);
        EasyPopup easyPopup = ShowAccountLayout.showPop(mActivity, et_money);
        ShowAccountLayout showAccountPop = (ShowAccountLayout) easyPopup.getContentView();
        showAccountPop.setAccountImage(this, Utils.checkNull(account.getAvatar()));
        showAccountPop.setAccountName(Utils.checkNull(account.getUserName()));
        showAccountPop.setOnClickCommit((View v) -> {
            easyPopup.dismiss();
            commitCash(account.getCardType() + "");
        });

        showAccountPop.setOnClickChangeAccount((View v) -> {
            easyPopup.dismiss();
            wxAuth();
        });
    }

    /**
     * 提交提现
     *
     * @param accountType
     */
    public void commitCash(String accountType) {
        money = et_money.getText().toString();//再次确认输入钱数
        hideSoftInput(mActivity, et_money);
        //如果当前密码为空 就再次弹出输入框
        if (tempPassword != null) {
            addPayBankRecord(tempPassword, accountType, money);
        } else {
            showInputPass(accountType);
        }
    }


    /**
     * 微信授权
     */
    public void wxAuth() {
        WXPayUtils build = new WXPayUtils.WXPayBuilder().build();
        try {
            build.getUserCode(mActivity, mCashBean.getWxAppId());
        } catch (MyException e) {
            showToast(e.getMessage());
        }
    }

    private String WX_TYPE = "1", ALI_TYPE = "2";

    /**
     * 微信授权成功,回调
     *
     * @param authResultEvent
     */
    @Subscribe(priority = 100)//011sh1Pi03TPAn1aStPi0SiFOi0sh1P9
    public void authFinish(AuthResultEvent authResultEvent) {
        EventBus.getDefault().cancelEventDelivery(authResultEvent);
        addAccountPop(WX_TYPE, authResultEvent.getCode());
    }

    public void showInputPass(String accountType) {
        passwordPopup = InputPayPasswordView.showPop(mActivity, tipText, (String password) -> {
            addPayBankRecord(password, accountType, money);
        });
    }

    String tempPassword;

    /**
     * 显示密码输入框
     *
     * @param WX_TYPE
     * @param accountToken
     */
    public void addAccountPop(String WX_TYPE, String accountToken) {
        hideSoftInput(mActivity, et_money);
        passwordPopup = InputPayPasswordView.showPop(mActivity, tipText, (String password) -> {
            tempPassword = password;
            passwordPopup.dismiss();
            commitAccountData(password, WX_TYPE, accountToken);
        });
    }

    /**
     * 添加账号
     *
     * @param password
     * @param cashType
     * @param accountToken
     */

    public void commitAccountData(String password, String cashType, String accountToken) {
        tempPassword = password;
        showLoadingDialog();
        addDisposableIoMain(userService.addAccount(password, cashType, accountToken), new DefaultConsumer<CashBean.Account>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<CashBean.Account> baseBean) {
                hideAlertDialog();
                mCashBean.addAccount(baseBean.getData());
                setWxInfo(baseBean.getData());
                //showAccount(baseBean.getData());
            }
        });
    }

    /**
     * 付款
     *
     * @param money
     * @param cashType
     */
    public void addPayBankRecord(String password, String cashType, String money) {
        tempPassword = null;
        showLoadingDialog();
        Observable<BaseResult<String>> baseResultObservable = userService.addPayBankRecord(password, cashType, money);
        addDisposableIoMain(baseResultObservable, new DefaultConsumer<String>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<String> baseBean) {
                hideAlertDialog();
                passwordPopup.dismiss();
                DialogController.showMustConfirmDialog(mActivity, "提示消息", baseBean.getMessage(), (View v) -> {
                    finish();
                });
            }
        });
    }


}
